package com.example.project.controller;

import com.example.project.common.Result;
import com.example.project.dto.form.UserLoginForm;
import com.example.project.dto.form.UserCreateForm;
import com.example.project.dto.vo.UserLoginVO;
import com.example.project.dto.vo.admin.AdminMenuVO;
import com.example.project.service.UserService;
import com.example.project.service.AdminRoleService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {
    /** 修改密码 */
    @PutMapping("/changePassword")
    public Result<Void> changePassword(@RequestBody java.util.Map<String, String> form,
                                      jakarta.servlet.http.HttpServletRequest request) {
        String oldPwd = form.get("oldPassword");
        String newPwd = form.get("newPassword");
        com.example.project.entity.User user = (com.example.project.entity.User) request.getSession().getAttribute("user");
        if (user == null) return Result.fail(400, "未登录");
        com.example.project.entity.User dbUser = userService.getUserEntityById(user.getId());
        if (!dbUser.getPassword().equals(oldPwd)) {
            return Result.fail(400, "历史密码错误");
        }
        dbUser.setPassword(newPwd);
        userService.updateUserPassword(dbUser);
        request.getSession().setAttribute("user", dbUser);
        return Result.ok();
    }
    /** 获取当前登录用户信息 */
    @GetMapping("/info")
    public Result<UserLoginVO> getUserInfo() {
        UserLoginVO user = userService.getCurrentUserInfo();
        return Result.ok(user);
    }
    /** 用户信息修改（保存） */
    @PutMapping("/info")
    public Result<Void> updateUserInfo(@RequestBody com.example.project.dto.form.UserInfoForm form,
                                      jakarta.servlet.http.HttpServletRequest request) {
        userService.updateUserInfo(form);
        // 更新 session 中的 user
        com.example.project.entity.User user = userService.getUserEntityById(form.getId());
        request.getSession().setAttribute("user", user);
        return Result.ok();
    }
    private final UserService userService;
    private final AdminRoleService adminRoleService;

    /** 用户登录 */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@Valid @RequestBody UserLoginForm form,
                                    jakarta.servlet.http.HttpServletRequest request) {
        UserLoginVO vo = userService.login(form);
        // 查询完整 User 实体并存入 session
        com.example.project.entity.User user = userService.getUserEntityById(vo.getUserId());
        request.getSession().setAttribute("user", user);
        return Result.ok(vo);
    }

//    /** 用户登录 */
//    @PostMapping("/login")
//    public Result<UserLoginVO> login(@Valid @RequestBody UserLoginForm form) {
//        return Result.ok(userService.login(form));
//    }

    /** 用户注册（无验证码） */
    @PostMapping("/register")
    public Result<Void> register(@Valid @RequestBody UserCreateForm form) {
        userService.register(form);
        return Result.ok();
    }

    /** 退出登录（无状态，直接成功） */
    @PostMapping("/logout")
    public Result<Void> logout() {
        return Result.ok();
    }

    /** 根据用户名获取菜单树（登录后调用）。游客返回游客菜单 */
    @GetMapping("/menus")
    public Result<java.util.List<AdminMenuVO>> getMenus(@RequestParam("username") String username) {
        // 查询用户角色ID集合
        java.util.List<com.example.project.dto.vo.admin.AdminRoleVO> roles = adminRoleService.listRolesByUser(username);
        java.util.List<AdminMenuVO> menus;
        if (roles == null || roles.isEmpty()) {
            // 游客菜单树
            menus = adminRoleService.getVisitorMenuTree();
        } else {
            java.util.List<Integer> rids = roles.stream().map(com.example.project.dto.vo.admin.AdminRoleVO::getId).toList();
            menus = adminRoleService.getMenuTreeByRoleIds(rids);
        }
        return Result.ok(menus);
    }

}
